package com.java.jian;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Jiange
 * @create 2021-04-09-12:47
 */
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建Cookie对象
        Cookie[] cookies = req.getCookies();

//        Cookie   cookie = new Cookie("name","建哥");
        Cookie cookie = new Cookie("name", "李子建");
        cookie.setMaxAge(1000);
//        cookie.setPath(req.getContextPath()+"/jian");
        //正数表示在指定的秒数后过期  负值表示浏览器一关 cookie就会被删除  0 表示马上删除cookie  默认值是-1
        //通知客户端保存Cookie
        resp.addCookie(cookie);//通过set-cookie:key=value 多个时 就是set-cookie:key1=value set-cookie:key2=value
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write("创建cookie成功");
        for (Cookie cookie1 : cookies) {
            System.out.println(cookie1.getMaxAge());
            resp.getWriter().write("cookie的值为"+cookie1.getName()+":"+cookie1.getValue()+"<br>");
        }

        //修改cookie 同名不同值  或者调用cookie.setValue() resp.addcookie()
    }
}
